<template>
    <div class="topic-detail">
        <div class="back-button" @click="goBack">
            <van-icon name="arrow-left" size="20" />
        </div>

        <div class="content-images">
            <img v-for="(img, index) in imageList" :key="index" :src="formatImageUrl(img)" class="content-image" />
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { gettopicDetail } from '@/api/home'
import { showToast } from 'vant'

const route = useRoute()
const router = useRouter()
const topicId = ref(route.query.id)
const imageList = ref([])
const loading = ref(true)

const formatImageUrl = (imgTag) => {
    const srcMatch = imgTag.match(/src="([^"]*)"/)
    if (srcMatch && srcMatch[1]) {
        let url = srcMatch[1]
        if (!url.startsWith('http')) {
            url = 'https:' + url
        }
        return url
    }
    return ''
}

const fetchTopicDetail = async () => {
    try {
        loading.value = true
        const response = await gettopicDetail({ id: topicId.value })
        if (response.errno === 0 && response.data.list[0]?.content) {

            const imgTags = response.data.list[0].content.match(/<img[^>]+>/g) || []
            imageList.value = imgTags
        } else {
            showToast('获取专题详情失败')
        }
    } catch (error) {
        console.error('获取专题详情失败:', error)
        showToast('网络错误，请重试')
    } finally {
        loading.value = false
    }
}


const goBack = () => {
    router.go(-1)
}

onMounted(() => {
    fetchTopicDetail()
})
</script>

<style scoped>
.topic-detail {
    min-height: 100vh;
    background-color: #f5f5f5;
    padding-bottom: 20px;
      min-width: 100vh;
}

.back-button {
    position: fixed;
    top: 10px;
    left: 10px;
    z-index: 100;
    width: 36px;
    height: 36px;
    background-color: rgba(0, 0, 0, 0.5);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
}

.content-images {
    padding-top: 10px;
}

.content-image {
    display: block;
    width: 100%;
    margin-bottom: 10px;
}
</style>